package com.mezizy.ifanmerchant;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.mezizy.ifanmerchant.global.Config;
import com.mezizy.ifanmerchant.global.GetNewOrderService;
import com.mezizy.ifanmerchant.global.Global;
import com.zxing.activity.CaptureActivity;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends ActionBarActivity {
    ImageView tabBtn01;
    ImageView tabBtn02;
    ImageView tabBtn03;
    View titleBar;
    LinearLayout titleBarParent;

    public static MainActivity instance;

    public MainActivity() {
        super();
        instance = this;
    }

    public static MainActivity getInstance() {
        return instance;
    }

    public static void setInstance(MainActivity instance) {
        MainActivity.instance = instance;
    }

    public void btnTabClick(View v) {

        switch (v.getId()) {
            case R.id.tabLayoutNewOrder:
                mViewPager.setCurrentItem(0);

                break;
            case R.id.tabLayoutOrderDone:
                mViewPager.setCurrentItem(1);

                break;
            case R.id.tabLayoutStoreManagement:
                mViewPager.setCurrentItem(2);

                break;

            default:
                break;

        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mViewPager.getCurrentItem() == 0) {
            NewOrderTab.startAsync();
        }
    }

    private ViewPager mViewPager;
    private FragmentPagerAdapter mAdapter;

    private List<Fragment> mFragments = new ArrayList<>();

    public void btn_num_click(View view) {

        final String orderPwd = PaymentTab.getInstance().edtNum.getText().toString();
        switch (view.getId()) {
            case R.id.btn1: {
                PaymentTab.getInstance().edtNum.setText(orderPwd + "1");
                break;
            }
            case R.id.btn2: {
                PaymentTab.getInstance().edtNum.setText(orderPwd + "2");
                break;
            }
            case R.id.btn3: {
                PaymentTab.getInstance().edtNum.setText(orderPwd + "3");
                break;
            }
            case R.id.btn4: {
                PaymentTab.getInstance().edtNum.setText(orderPwd + "4");
                break;
            }
            case R.id.btn5: {
                PaymentTab.getInstance().edtNum.setText(orderPwd + "5");
                break;
            }
            case R.id.btn6: {
                PaymentTab.getInstance().edtNum.setText(orderPwd + "6");
                break;
            }
            case R.id.btn7: {
                PaymentTab.getInstance().edtNum.setText(orderPwd + "7");
                break;
            }
            case R.id.btn8: {
                PaymentTab.getInstance().edtNum.setText(orderPwd + "8");
                break;
            }
            case R.id.btn9: {
                PaymentTab.getInstance().edtNum.setText(orderPwd + "9");
                break;
            }
            case R.id.btn0: {
                PaymentTab.getInstance().edtNum.setText(orderPwd + "0");
                break;
            }
            case R.id.btncheck: //付款   TODO * 付款
                Global.showProgress(this, "付款中");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (Global.orderAuth(orderPwd)) {
                            Global.showToast("付款成功！", getInstance());
                        } else {
                            Global.showToast("付款失败！", getInstance());

                        }
                        Global.dismissProgress();
                    }
                }).start();

                PaymentTab.getInstance().edtNum.setText("");

                break;
            case R.id.btnBackSpace: //退格
                if (orderPwd.length() == 0) break;

                PaymentTab.getInstance().edtNum.setText(orderPwd.substring(0, orderPwd.length() - 1));
                break;

        }
        if (PaymentTab.getInstance().edtNum.getText().toString().length() > Config.ORDER_NUM_MAX) {
            PaymentTab.getInstance().edtNum.setText(orderPwd.substring(0, Config.ORDER_NUM_MAX));

        }

    }

    public void resetBtn() {
        tabBtn01.setImageResource(R.drawable.tab_new_order_release);
        tabBtn02.setImageResource(R.drawable.tab_payment_release);
        tabBtn03.setImageResource(R.drawable.tab_management_release);

        if (titleBar == null || titleBarParent == null) {
            titleBar = findViewById(R.id.relativeTitleBar);
            titleBarParent = ((LinearLayout) titleBarParent.getParent());
        }

        switch (mViewPager.getCurrentItem()) {
            case 0:
                tabBtn01.setImageResource(R.drawable.tab_new_order_pressed);
                NewOrderTab.startAsync();
                if (titleBarParent.getChildAt(0)!= titleBar) {
                    titleBarParent.addView(titleBar,0);
                }

                break;
            case 1:
                tabBtn02.setImageResource(R.drawable.tab_payment_pressed);
                if (titleBarParent.getChildAt(0)!= titleBar) {
                    titleBarParent.addView(titleBar,0);
                }

                break;
            case 2:
                if (titleBarParent.getChildAt(0)== titleBar) {
                    titleBarParent.removeView(titleBar);

                }

                tabBtn03.setImageResource(R.drawable.tab_management_pressed);
                break;


        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }

        Bundle extras = data.getExtras();
        if (extras == null) {
            return;
        }

        String pwd = "";
//        Log.i("MainActivity", pwd=extras.getString("result"));
        pwd = extras.getString("result");
//        Global.showToast(extras.getString("result"),Toast.LENGTH_LONG);

        Global.showProgress(this, "付款中");
        final String finalPwd = pwd;
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (Global.orderAuth(finalPwd)) {
                    Global.showToast("付款成功！", getInstance());
                } else {
                    Global.showToast("付款失败！", getInstance());

                }
                Global.dismissProgress();
            }
        }).start();


    }

    //扫描QR-Code
    public void btnQRCodeClicked(View view) {
        //1可以换成别的，必须大于0
        startActivityForResult(new Intent(MainActivity.this, CaptureActivity.class), 1);
    }


    @Override
    protected void onStart() {
        super.onStart();
        Global.appContext = getApplicationContext();

        //TODO test 之后移除 默认的商店ID
        Global.merchantId = "m001";
        Global.merchantPwdSha = "123";

        Global.appState = Config.FOREGROUND;

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        getSupportActionBar().hide();

        mViewPager = (ViewPager) findViewById(R.id.viewPager);
        tabBtn01 = (ImageView) findViewById(R.id.tabStores);
        tabBtn02 = (ImageView) findViewById(R.id.tabOrders);
        tabBtn03 = (ImageView) findViewById(R.id.tabSelfInf);
        if (titleBar == null || titleBarParent == null) {
            titleBar = findViewById(R.id.relativeTitleBar);
            titleBarParent = ((LinearLayout) titleBar.getParent());
        }


        initView();

        mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {

            @Override
            public int getCount() {
                return mFragments.size();
            }

            @Override
            public Fragment getItem(int arg0) {
                return mFragments.get(arg0);
            }
        };

        mViewPager.setAdapter(mAdapter);

        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            private int currentIndex;

            @Override
            public void onPageSelected(int position) {
                resetBtn();
                currentIndex = position;


            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
        ((ImageView) findViewById(R.id.btnQR)).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_CANCEL:
                        ((ImageView) findViewById(R.id.btnQR)).setImageResource(R.drawable.payment_qr);
                        break;
                    case MotionEvent.ACTION_DOWN:
                        ((ImageView) findViewById(R.id.btnQR)).setImageResource(R.drawable.payment_qr_pressed);

                        break;
                    case MotionEvent.ACTION_UP:
                        ((ImageView) findViewById(R.id.btnQR)).setImageResource(R.drawable.payment_qr);
                        break;
                }
                return false;
            }
        });


        startService(new Intent(GetNewOrderService.ACTION));

    }

    private void initView() {

        NewOrderTab newOrderTab = new NewOrderTab();
        PaymentTab paymentTab = new PaymentTab();
        StoreManagementTab storeManagementTab = new StoreManagementTab();


        mFragments.add(newOrderTab);
        mFragments.add(paymentTab);
        mFragments.add(storeManagementTab);
    }

    @Override
    protected void onPause() {
        super.onPause();
        Global.appState = Config.BACKGROUND;
    }

    @Override
    public void onBackPressed() {
        if (mViewPager.getCurrentItem() == 2 && StoreManagementTab.webView.canGoBack()) {
            StoreManagementTab.webView.goBack();
            ;
        } else {
            Intent startMain = new Intent(Intent.ACTION_MAIN);
            startMain.addCategory(Intent.CATEGORY_HOME);
            startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(startMain);
            System.exit(0);
            super.onBackPressed();
        }


    }


}